#include "stdafx.h"
#include "NetManage.h"
#include "CommandDefine.h"

SharedPointer<CNetConnectManage> CNetConnectManage::m_pNetConnectMange;
CNetConnectManage::CNetConnectManage()
{
}


CNetConnectManage::~CNetConnectManage()
{
}

void CNetConnectManage::UpdateDevice(CNetConnect* pConnect)
{
	if (pConnect->GetDeviceId() > 0)
	{
		PNetConnect pNetIn;
		for (PNetConnect&pNet : m_lsConncetNotInit)
		{
			if (pNet.get() == pConnect)
			{
				pNetIn = pNet;
				m_lsConncetNotInit.remove(pNet);
				break;
			}
		}
		if (!pNetIn.get())
		{
			assert(false);
		}
		else
		{
			m_connections[pNetIn->GetDeviceId()] = pNetIn;
		}

	}
}

void CNetConnectManage::Start(PNetConnect c)
{
	m_lsConncetNotInit.push_back(c);
	c->Start();
}

void CNetConnectManage::Stop(PNetConnect c, int WaitSecond)
{
	c->Close(WaitSecond);
	if (m_connections.find(c->GetDeviceId()) != m_connections.end())
	{
		m_connections.remove(c->GetDeviceId());
	}
	else
	{
		m_lsConncetNotInit.remove(c);
	}
}

void CNetConnectManage::Stop_All()
{
	for (QMap<int, PNetConnect>::iterator pos = m_connections.begin(); pos!= m_connections.end(); ++pos)
	{
		(pos.value())->Close();
	}
	for (PNetConnect&pNet : m_lsConncetNotInit)
	{
		pNet->Close();
	}
	m_connections.clear();
	m_lsConncetNotInit.clear();
}

bool CNetConnectManage::PushNewDataWrite(SharedPointer<ZMVector<unsigned char>>& buffer)
{
	bool ret = false;
	int idDevice = CCommandDefine::GetDeviceID(*buffer), typeDevice = CCommandDefine::GetDeviceType(*buffer);
	if (idDevice > 0)
	{
		if( m_connections.find(idDevice) != m_connections.end())
		{
			m_connections[idDevice]->PushNewDataWrite(buffer);
			ret = true;
		}
	}
	if (!ret && typeDevice > 0)
	{
		for (QMap<int, PNetConnect>::iterator pos = m_connections.begin(); pos != m_connections.end(); ++pos)
		{
			if (pos.value()->GetDevicType() == typeDevice)
			{
				SharedPointer<ZMVector<unsigned char>> pData = SharedPointer<ZMVector<unsigned char>>(new ZMVector<unsigned char>(*buffer));
				pos.value()->PushNewDataWrite(pData);
				ret = true;
			}
		}
	}
	if (!ret&& idDevice == 0 && typeDevice == 0)
	{
		for (QMap<int, PNetConnect>::iterator pos = m_connections.begin(); pos != m_connections.end(); ++pos)
		{
				SharedPointer<ZMVector<unsigned char>> pData = SharedPointer<ZMVector<unsigned char>>(new ZMVector<unsigned char>(*buffer));
				pos.value()->PushNewDataWrite(pData);
				ret = true;
		}
		for (PNetConnect&pNet : m_lsConncetNotInit)
		{
			SharedPointer<ZMVector<unsigned char>> pData = SharedPointer<ZMVector<unsigned char>>(new ZMVector<unsigned char>(*buffer));
			pNet->PushNewDataWrite(pData);
			ret = true;
		}
	}
	return ret;
}